<?php

namespace app\admin\model\goods;

use app\common\model\Category;
use fast\Http;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Log;
use think\Model;


class Goods extends Model
{
    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = 'mtime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
//        'mtime_text',
//        'ctime_text'
    ];

    protected $gatherRule;

    public function getTmallGoods($keyword,$page,$price){
        $config=Config::get("data_conf");
        $url=$config['TmallUri'].'?apikey='.$config['TmallApiKey'].'&order=s&channel=default&tab=newmall&keyword='.urlencode($keyword).'&page='.$page;
        $url.='&startPrice='.$price;
        return Http::get($url);
    }

    /**
     * @Explain :抓取天猫商品数据
     * @param $cateid
     * @return bool|int|string
     * @Date : 2020/8/29 17:24
     * @Author : 河南邦耀网络科技有限公司
     */
    public function saveTmallGoods($cateid,$pname=''){
        set_time_limit(0);
        $res=true;
        $cateInfo=Category::get($cateid);
        if(empty($cateInfo)) return false;
        $this->setGatherRule($cateInfo['pid']);
        $page=1;
        $maxNum=$this->gatherRule['num']/10;
       do{
           if(!empty($cateInfo['nickname'])){
               $keyword=$cateInfo['nickname'];
           }else{
               $keyword=$cateInfo['name'];
           }
           echo date('Ymd H:i').'-开始写入分类'.$keyword." \n";
           $result=$this->getTmallGoods($keyword,$page,$this->gatherRule['price']);
           if($result){
               $goodsList=json_decode($result,true);
           }else{
               return false;
           }
            foreach ($goodsList['data'] as $row){
                $item=$this->getItem($row['id']);
                $sellCount=$this->parseSellCount($row['sales']);
                if(!isset($item['item']) || $sellCount<$this->gatherRule['sales']){
                    continue;
                }
                if(isset($item['item']['desc'])){
                    $strarr=explode('</img>',$item['item']['desc']);
                    $content=array_map('strip_tags',$strarr);
                }else{
                    $content='';
                }

                if(preg_match('/^(\d)*$/',$row['sales'],$arr)){
                    $row['sales']='月销'.$arr[0].'笔';
                }
                $data=[
                    'goodsid'=>$row['id'],
                    'sellerId'=>$row['sellerId'],
                    'seller'=>$row['seller'],
                    'title'=>$row['title'],
                    'image'=>isset($row['imageUrls'][0])?\fast\Utils::tmallThumb($row['imageUrls'][0]):'',
                    'price'=>$row['price'],
                    'sales'=>$row['sales'],
                    'sellCount'=>$sellCount,
                    'commentCount'=>$row['commentCount'],
                    'location'=>$row['location'],
                    'category'=>$item['item']['categoryId'],
                    'SelfCateId'=>$cateid,
                    'content'=>json_encode($item['item']['descImgs'],JSON_UNESCAPED_UNICODE),
                    'ctime'=>time(),
                ];
                try {
                    if (empty(parent::get(['goodsid' => $row['id']]))) {
                        $res = $this->insert($data);
                    }else{
                        $res= $this->update($data,['goodsid'=>$row['id']]);
                    }
                } catch (DbException $e) {
                }
                $newItem=[
                    'itemId'=>$item['item']['itemId'],
                    'priceRange'=>$item['item']['priceRange'],
                    'sku'=>json_encode($item['item']['sku'],JSON_UNESCAPED_UNICODE),
                    'desc'=>$item['item']['desc'],
                    'images'=>json_encode($item['item']['images']),
                    'videos'=>isset($item['item']['videos'])?json_encode($item['item']['videos']):'',
                    'categoryId'=>$item['item']['categoryId'],
                    'vagueSellCount'=>$item['item']['vagueSellCount'],
                    'url'=>$item['item']['url'],
                    'groupProps'=>isset($item['item']['groupProps'])?json_encode($item['item']['groupProps'],JSON_UNESCAPED_UNICODE):'[]',
                    'props'=>json_encode($item['item']['props'],JSON_UNESCAPED_UNICODE),
                    'skuid'=>$item['item']['itemId'],
                    'delivery'=>$item['item']['delivery'],
                    'consumerProtection'=>json_encode($item['item']['consumerProtection'],JSON_UNESCAPED_UNICODE),
                    'ctime'=>time(),
                ];
                if(empty(Db::table('pt_goods_sku')->find(['itemId'=>$item['item']['itemId']]))){
                    $res=Db::table('pt_goods_sku')->insert($newItem,true);
                }
                $data=[];
                foreach ($item['item']['sku'] as $sku){
                    if(empty(Db::table('pt_goods_skudetail')->find(['skuId'=>$sku['skuId']]))) {
                       if(!is_numeric($sku['price'])) continue;
                        $data[]=[
                            'goodsId'=>$item['item']['itemId'],
                            'skuId' =>$sku['skuId'],
                            'title' =>isset($sku['skuName'])?$sku['skuName']:'',
                            'price' =>$sku['price'],
                            'image' =>isset($sku['image'])?\fast\Utils::tmallThumb($sku['image']):'',
                            'propPath' =>$sku['propPath'],
                            'ctime' =>time()
                         ];
                    }
                }
                $res = Db::table('pt_goods_skudetail')->insertAll($data);
            }
            echo '已写入'.$page.'页 '." \n";
            $page++;
        }while ($goodsList['hasNext']==true && $page<$maxNum);
        echo date('Ymd H:i').'-成功写入分类'.$keyword." \n";
        return $res;
    }

    public function getItem($id){
        $config=Config::get("data_conf");
        $url=$config['TmallItemUri'].'?apikey='.$config['TmallApiKey'].'&itemId='.$id;
        $item= Http::get($url);
        $item=json_decode($item,true);
        return $item['data'];
    }
    public function saveItemContent($id,$item){
        static $i=0;
        $data['content']=json_encode($item['item']['descImgs'],JSON_UNESCAPED_UNICODE);
        $res= $this->update($data,['goodsid'=>$id]);

        if($res){
            echo $i++."成功更新商品ID[{$id}] \n";
        }
    }

    public function getMtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['mtime']) ? $data['mtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['ctime']) ? $data['ctime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setMtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * @Explain :获取抓取配置信息
     * @param $cateid 分类id
     * @Date : 2020/9/21 10:09
     * @Author : 河南邦耀网络科技有限公司
     */

    private function setGatherRule($cateid){
        $cateModel=new Category();
        $pinfo=$cateModel->where('id',$cateid)->find();
        $id=$cateModel->where('id',$pinfo['pid'])->value('id');
        $config=Config::get("caiji");

        if(array_key_exists($id,$config)){
            $this->gatherRule=$config[$id];
        }else{
            $this->gatherRule=[
                'price' =>50,
                'sales' =>10,
                'num' =>200,
            ];
        }
    }


    private function parseSellCount($str){
        $num=0;
        if(preg_match('/\d+/',$str,$arr)){
            $num=$arr[0];
        }
        if(strpos($str,'万')){
            $num*=10000;
        }
        return $num;
    }



}
